/*
用户模板
定义了用户模板类
 */

import prompt from '@ohos.prompt';
import {DA_HELPER,URI} from './dataAbilityHelperModel';
import dataAbility from '@ohos.data.dataAbility';
import {simpleBook} from './bookModel'

const TAG:string = 'UserModel'

/*
默认管理员id:0000000000000
        name:admin
        password:admin

       {id:"0000000000000",permission:2,name:"admin",password:"admin",token:"1234567890"}
 */
export class User{
    /**
     * 用户类型,["reader","admin"]
     */
    public userType: string;
    /**
    *用户id,13位字符串（学号）
    */
    public id: string;
    /**
     *用户名,不超过20位字符
     */
    public userName: string;
    /**
     * 用户密码,不超过20个字符
     */
    public userPassword: string;
    /**
     * 和服务器验证的标识,十位字符串
     */
    public token: string;
    /**
     * 取值范围[0,1,2],分别为基础权限,普通管理权限,默认管理权限
     */
    public permission:number;
    /**
     * 借阅列表,'{n}||{"bookName":"xxxx","id":“xxxx”,"backTime":“xxxx”}',n表示数量，用"||"分隔;JSON格式注意元素要用双引号包裹
     */
    public lend:string;
    /**
     * 构造函数
     */
    constructor(
        usertype:string='reader',id:string='0000000000000',
        userName:string='默认用户名',userPassword:string='00000000',){
        this.userType = usertype;
        this.id = id;
        this.userName = userName;
        this.userPassword = userPassword;
        if(usertype == 'admin'){
            if(id == '1234567891011'){
                this.permission = 2;
            }
            this.permission = 1;
        }
        else{
            this.permission = 0;
        }
        this.lend = '{0}';
    }
    /**
     * 返回当前用户token
     */
    getToken(){
        return this.token;
    }
    setToken(token:string){
        this.token = token;
    }
    /**
    *返回用户权限,取值范围[0,1,2],分别为基础权限,普通管理权限,默认管理权限
    */
    getPermission(){
        if(this.permission == null){
            this.permission = 0;
        }
        return this.permission;
    }
    /**
     * 用户登录，返回是否成功
     */
    login(){
        this.token = '1234567890';
        return user_login(this);
    }
    /**
     * 用户注册，返回是否成功
     */
    register(){
        this.token = '1234567890';
        return user_register(this);
    }
    /**
     * 用户登出，返回是否成功
     */
    signOut(){
        return user_signOut(this);
    }
    /**
     * 读者借阅书籍
     * @param bookId
     */
    lendBook(bookId:string,bookName:string){
        if(this.userType == 'admin'){
            console.info(`${TAG}::lendBook err:userTypeError`);
            prompt.showToast({message:'书籍借阅失败:用户类型错误'});
            return;
        }
        let simpleBook:simpleBook = {
            bookName:bookName,
            id:bookId,
            backTime:'2022/08/27',
        };
        //解析lend
        let lendNum:number = Number(this.lend.match(/{\d+?}/));
        lendNum += 1;
        let newLend:string = `{${lendNum}}`;
        let lendStr = this.lend.split('||')//分隔符
        for(let i = 1;i < (lendNum - 1);i++){
            newLend = newLend + '||' + lendStr[i];
        }
        newLend = newLend + '||' + JSON.stringify(simpleBook);
        let predicates = new dataAbility.DataAbilityPredicates();
        let valuesBucket = {
            "lend":newLend,
        };
        predicates.equalTo('id',this.id);
        DA_HELPER.update(
            URI.User_reader_URI,
            valuesBucket,
            predicates,
            (err,data)=>{
                if(err.code){
                    console.info(`${TAG} update reader(lend) err:${JSON.stringify(err)}`);
                    prompt.showToast({message:'user数据库更新出错'});
                    return;
                }
                this.lend = newLend;
                console.info(`${TAG} update reader(lend) successful,data:${data}`);
            }
        )
    }
    /**
     * 读者归还书籍
     * @param bookId
     */
    returnBook(bookId:string){
        if(this.userType == 'admin'){
            console.info(`${TAG}::lendBook err:userTypeError`);
            prompt.showToast({message:'书籍归还失败:用户类型错误'});
            return;
        }
        //解析lend
        let lendNum:number = Number(this.lend.match(/{\d+?}/));
        if(lendNum == 0){
            console.info(`${TAG}::lendBook err:userTypeError`);
            prompt.showToast({message:'书籍归还失败:用户无借阅记录'});
            return;
        }
        lendNum -= 1;
        let newLend:string = `{${lendNum}}`;
        let lendStr:string[] = this.lend.split('||')//分隔符
        let isInLend:boolean = false;
        for(let i = 1;i < (lendNum + 1);i++){
            if(JSON.parse(lendStr[i]).id == bookId){
                isInLend = true;
            }
            else{
                newLend = newLend + '||' + lendStr[i];
            }
        }
        if(isInLend == false){
            console.info(`${TAG}::lendBook err:userTypeError`);
            prompt.showToast({message:'书籍归还失败:用户未借阅该书籍'});
            return;
        }
        let predicates = new dataAbility.DataAbilityPredicates();
        let valuesBucket = {
            "lend":newLend,
        };
        predicates.equalTo('id',this.id);
        DA_HELPER.update(
            URI.User_reader_URI,
            valuesBucket,
            predicates,
            (err,data)=>{
                if(err.code){
                    console.info(`${TAG} update reader(lend) err:${JSON.stringify(err)}`);
                    prompt.showToast({message:'user数据库更新出错'});
                    return;
                }
                this.lend = newLend;
                console.info(`${TAG} update reader(lend) successful,data:${data}`);
            }
        )

        //todo 待补全:更新管理员待办事项 : addTodoItem()
    }
    reset_name(name:string){
        let uri:string;
        if(this.userType == 'admin'){
            uri = URI.User_admin_URI;
        }
        else{
            uri = URI.User_reader_URI;
        }
        let predicates = new dataAbility.DataAbilityPredicates();
        predicates.equalTo('id',this.id);
        let valuesBucket = {
            "name":name,
        }
        DA_HELPER.update(
            uri,
            valuesBucket,
            predicates,
            (err,data)=>{
                if(err.code){
                    console.info(`update ${this.userType}(name:${name}) err:${JSON.stringify(err)}`);
                    prompt.showToast({message:'user数据库更新出错'});
                    return;
                }
                this.userName = name;
                console.info(`update ${this.userType}(name:${name}) successful,data:${data}`);
                prompt.showToast({message:'user数据库更新成功'});
            }
        )
    }
    reset_password(password:string){
        let uri:string;
        if(this.userType == 'admin'){
            uri = URI.User_admin_URI;
        }
        else{
            uri = URI.User_reader_URI;
        }
        let predicates = new dataAbility.DataAbilityPredicates();
        predicates.equalTo('id',this.id);
        let valuesBucket = {
            "password":password,
        }
        DA_HELPER.update(
            uri,
            valuesBucket,
            predicates,
            (err,data)=>{
                if(err.code){
                    console.info(`update ${this.userType}(password:${password}) err:${JSON.stringify(err)}`);
                    prompt.showToast({message:'user数据库更新出错'});
                    return;
                }
                this.userPassword = password;
                console.info(`update ${this.userType}(password:${password}) successful,data:${data}`);
                prompt.showToast({message:'user数据库更新成功'});
            }
        )
    }
}
export function addAdmin(id:string,name:string,password:string){
    let predicates = new dataAbility.DataAbilityPredicates();
    predicates.equalTo('id',id);
    DA_HELPER.query(
        URI.User_admin_URI,
        ["id","name"],
        predicates,
        (err,resultSet)=>{
            if (err.code){
                console.info("addAdmin query failed, err: " + JSON.stringify(err));
                prompt.showToast({message:"操作失败：数据库查询出错"});
                return;
            }
            console.info("addAdmin query successful, rowCount:" + resultSet.rowCount);
            if(resultSet.rowCount > 0){
                resultSet.close();
                prompt.showToast({message:"操作失败：该账号已存在"});
                console.info("addAdmin failed, rowCount:" + resultSet.rowCount);
                return;
            }
            else{
                resultSet.close();
                let valuesBucket = {
                    "id":id,
                    "permission":1,
                    "name":name,
                    "password":password,
                    "token":'1234567890',
                }
                DA_HELPER.insert(
                    URI.User_admin_URI,
                    valuesBucket,
                    (err,data)=>{
                        if(err.code){
                            console.info("addAdmin insert failed,err:"+JSON.stringify(err));
                            prompt.showToast({message:"操作失败:数据库插入出错"});
                            return;
                        }
                        console.info("addAdmin insert successful, data:" + data);
                        prompt.showToast({message:"操作成功"});
                    }
                )
            }
        }
    )
}
export function deleteAdmin(id:string){
    let predicates = new dataAbility.DataAbilityPredicates();
    predicates.equalTo('id',id);
    DA_HELPER.query(
        URI.User_admin_URI,
        ["id","name"],
        predicates,
        (err,resultSet)=>{
            if (err.code){
                console.info("deleteAdmin query failed, err: " + JSON.stringify(err));
                prompt.showToast({message:"操作失败：数据库查询出错"});
                return;
            }
            console.info("deleteAdmin query successful, rowCount:" + resultSet.rowCount);
            if(resultSet.rowCount > 0){
                resultSet.close();
                DA_HELPER.delete(
                    URI.User_admin_URI,
                    predicates,
                    (err,data)=>{
                        if (err.code){
                            console.info("deleteAdmin delete failed, err: " + JSON.stringify(err));
                            prompt.showToast({
                                message:"操作失败:数据库删除操作出错",
                            });
                            return;
                        }
                        console.info("deleteAdmin delete successful, data: " + data);
                        prompt.showToast({message:'操作成功'});
                    }
                )
            }
            else{
                resultSet.close();
                prompt.showToast({message:"操作失败:该账号不存在"});
                console.info("deleteAdmin failed, rowCount:" + resultSet.rowCount);
                return;
            }
        }
    )
}
export function addReader(id:string,name:string,password:string){
    let predicates = new dataAbility.DataAbilityPredicates();
    predicates.equalTo('id',id);
    DA_HELPER.query(
        URI.User_reader_URI,
        ["id","name"],
        predicates,
        (err,resultSet)=>{
            if (err.code){
                console.info("addReader query failed, err: " + JSON.stringify(err));
                prompt.showToast({message:"操作失败：数据库查询出错"});
                return;
            }
            console.info("addReader query successful, rowCount:" + resultSet.rowCount);
            if(resultSet.rowCount > 0){
                resultSet.close();
                prompt.showToast({message:"操作失败：该账号已存在"});
                console.info("addReader failed, rowCount:" + resultSet.rowCount);
                return;
            }
            else{
                resultSet.close();
                let valuesBucket = {
                    "id":id,
                    "permission":0,
                    "name":name,
                    "password":password,
                    "token":'1234567890',
                    "lend":'{0}',
                }
                DA_HELPER.insert(
                    URI.User_reader_URI,
                    valuesBucket,
                    (err,data)=>{
                        if(err.code){
                            console.info("addReader insert failed,err:"+JSON.stringify(err));
                            prompt.showToast({message:"操作失败:数据库插入出错"});
                            return;
                        }
                        console.info("addReader insert successful, data:" + data);
                        prompt.showToast({message:"操作成功"});
                    }
                )
            }
        }
    )
}
export function deleteReader(id:string){
    let predicates = new dataAbility.DataAbilityPredicates();
    predicates.equalTo('id',id);
    DA_HELPER.query(
        URI.User_reader_URI,
        ["id","name"],
        predicates,
        (err,resultSet)=>{
            if (err.code){
                console.info("deleteReader query failed, err: " + JSON.stringify(err));
                prompt.showToast({message:"操作失败：数据库查询出错"});
                return;
            }
            console.info("deleteReader query successful, rowCount:" + resultSet.rowCount);
            if(resultSet.rowCount > 0){
                resultSet.close();
                DA_HELPER.delete(
                    URI.User_reader_URI,
                    predicates,
                    (err,data)=>{
                        if (err.code){
                            console.info("deleteReader delete failed, err: " + JSON.stringify(err));
                            prompt.showToast({
                                message:"操作失败:数据库删除操作出错",
                            });
                            return;
                        }
                        console.info("deleteReader delete successful, data: " + data);
                        prompt.showToast({message:'操作成功'});
                    }
                )
            }
            else{
                resultSet.close();
                prompt.showToast({message:"操作失败:该账号不存在"});
                console.info("deleteReader failed, rowCount:" + resultSet.rowCount);
                return;
            }
        }
    )
}
/**
 * 用户登录，返回是否成功
 * @param user
 */
export function user_login(user:User):boolean{
    //未完成
    return true;
}
/**
 * 用户注册，返回是否成功
 * @param user
 */
export function user_register(user:User):boolean{
    user.permission = 0;
    //未完成
    return true;
}
/**
 * 用户登出，返回是否成功
 * @param user
 */
export function user_signOut(user:User):boolean{
    //未完成
    return true;
}
/**
 * 待办事项
 */
export class todoItem{
    public todoType:string;
    public todoText:string;
    /**
     * 事件id,12位字符串,前8位表示日期,后4位编号"202208010001"
     */
    public itemId:string;
    constructor(todoType:string,todoText:string,itemId){
        this.todoText = todoText;
        this.todoType = todoType;
        this.itemId = itemId;
    }
}
/**
 * 关闭待办事项
 * @param itemId
 */
export function closeTodoItem(itemId:string){
    let predicates = new dataAbility.DataAbilityPredicates();
    predicates.equalTo('todoId',itemId)
    DA_HELPER.delete(
        URI.User_adminTodo_URI,
        predicates,
        (err,data)=>{
            if (err.code){
                console.info("todoItem delete failed, err: " + JSON.stringify(err));
                prompt.showToast({
                  message:"待办事件删除失败：数据库删除操作出错",
                });
                return;
            }
            console.info("todoItem delete successful, data: " + data);
            prompt.showToast({message:'待办事件已删除(完成)'});
        }
    )

}
/**
 * 更新待办事项
 */
export function getTodoItem(point:any):void{
    //point.list = todoItem
    let predicates = new dataAbility.DataAbilityPredicates();
    let columns = ["todoType","todoId","todoText"];
    let list:todoItem[];
    DA_HELPER.query(
        URI.User_adminTodo_URI,
        columns,
        predicates,
        (err,resultSet)=>{
            if (err.code){
                console.info("todoItem get failed, err: " + JSON.stringify(err));
                prompt.showToast({
                    message:"待办事项查询失败：数据库查询操作出错",
                });
                return;
            }
            console.info("todoItem get successful, rowCount:" + resultSet.rowCount);
            if(resultSet.rowCount > 0){
                resultSet.goToFirstRow();
                do{
                    list.push({
                        todoType:resultSet.getString(0),
                        itemId:resultSet.getString(1),
                        todoText:resultSet.getString(2),
                    })
                }
                while(resultSet.goToNextRow());
                resultSet.close();
                point.list = list;
                console.info("todoItem update successful, rowCount:" + resultSet.rowCount);
                prompt.showToast({
                    message:'待办事项更新成功',
                });
            }
            else{
                list = [
                    {
                        todoType:'读者还书1',
                        todoText:'书籍名称xxxx,书籍位置xxxx',
                        itemId:'202208010001',
                    },
                    {
                        todoType:'读者还书2',
                        todoText:'书籍名称xxxx,书籍位置xxxx',
                        itemId:'202208010001',
                    },
                    {
                        todoType:'读者还书3',
                        todoText:'书籍名称xxxx,书籍位置xxxx',
                        itemId:'202208010001',
                    },
                    {
                        todoType:'读者还书4',
                        todoText:'书籍名称xxxx,书籍位置xxxx',
                        itemId:'202208010001',
                    },
                ];
                point.list = list;
                console.info("todoItem update successful, rowCount:" + resultSet.rowCount);
                prompt.showToast({
                    message:"待办事项更新成功(未找到记录)(使用默认记录)",
                });
            }
        }
    )
}

export function addTodoItem(todoType:string,itemId:string,todoText:string):void{
    let valuesBucket = {
        "todoType":todoType,
        "todoId":itemId,
        "todoText":todoText,
    };
    DA_HELPER.insert(
        URI.User_adminTodo_URI,
        valuesBucket,
        (err,data)=>{
            if(err.code){
                console.info(`${TAG} addTodoItem err` + JSON.stringify(err));
                prompt.showToast({message:"新增待办事项失败:数据库插入出错"});
                return;
            }
            console.info(`${TAG} addTodoItem successful,data:${data}`);
        }
    )
}